<script setup lang="ts">
import { reqAddOrUpdateAttr, reqAttr, reqRemoveAttr } from '@/apis/product/attr'
import { useCategoryStore } from '@/store/modules/category'
import type { AttrList, Attr, AttrValue } from '@/types/attr'
import { ElMessage } from 'element-plus'
import { nextTick, ref, watch } from 'vue'

//引入仓库
const categoryStore = useCategoryStore()
//存储已有属性
const attrList = ref<AttrList>([])
const getAttr = async () => {
  const res = await reqAttr(
    categoryStore.c1Id,
    categoryStore.c2Id,
    categoryStore.c3Id,
  )
  if (res.code === 200) {
    attrList.value = res.data
  }
}
//监听c3Id
watch(
  () => categoryStore.c3Id,
  () => {
    attrList.value = []
    if (!categoryStore.c3Id) return
    getAttr()
  },
)
//定义卡片组件切换
const scene = ref(0)
//收集请求参数
const attrParmas = ref<Attr>({
  //属性名称
  attrName: '',
  //三级分类id
  categoryId: '',
  //属性值对象
  attrValueList: [],
  //分类层级
  categoryLevel: 3,
})
//添加属性
const addAttr = () => {
  //清空数据
  Object.assign(attrParmas.value, {
    //属性名称
    attrName: '',
    //三级分类id
    categoryId: categoryStore.c3Id,
    //属性值对象
    attrValueList: [],
    //分类层级
    categoryLevel: 3,
  })
  //切换卡片组件
  scene.value = 1
  //收集三级分类的id
}
//修改已有属性
const updateAttr = (row: Attr) => {
  //切换卡片组件
  scene.value = 1
  //深拷贝
  Object.assign(attrParmas.value, JSON.parse(JSON.stringify(row)))
}
//删除属性
const deleteAttr = async (attrId: number) => {
  const res = await reqRemoveAttr(attrId)
  if (res.code === 200) {
    // 成功提示
    ElMessage.success('删除成功')
    //重新获取数据
    getAttr()
  } else {
    ElMessage.error('删除失败')
  }
}
//添加属性值
const addAttrValue = () => {
  //数组添加属性值对象
  attrParmas.value.attrValueList.push({
    valueName: '',
    flag: true,
  })
  //表单聚焦
  nextTick(() => {
    inputArr.value[attrParmas.value.attrValueList.length - 1].focus()
  })
}
// 取消按钮回调
const cancel = () => {
  scene.value = 0
}
//保存按钮的回调
const saveAttr = async () => {
  //发起请求
  const res = await reqAddOrUpdateAttr(attrParmas.value)
  if (res.code === 200) {
    //切换场景
    scene.value = 0
    //提示信息
    ElMessage.success(attrParmas.value.id ? '修改成功' : '添加成功')
    //重新获取数据
    getAttr()
  } else {
    //提示信息
    ElMessage.success(attrParmas.value.id ? '修改失败' : '添加失败')
  }
}
//属性值表单失去焦点
const toLook = (row: AttrValue, $index: number) => {
  //非法情况
  if (row.valueName.trim() == '') {
    attrParmas.value.attrValueList.splice($index, 1)
    ElMessage.error('属性值不能为空')
    return
  }
  const repeat = attrParmas.value.attrValueList.find((item) => {
    if (item !== row) {
      return (item.valueName = row.valueName)
    }
  })
  if (repeat) {
    attrParmas.value.attrValueList.splice($index, 1)
    ElMessage.error('属性值不能重复')
    return
  }
  row.flag = false
}
//切换编辑模式
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  //表单聚焦
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}

//存储组件实例
const inputArr = ref<any>([])
</script>

<template>
  <div>
    <!-- 顶部分类组件 -->
    <Category :scene="scene" />
    <!-- 主体内容 -->
    <el-card style="margin: 10px 0">
      <div v-show="scene == 0">
        <!-- 顶部按钮 -->
        <el-button
          type="primary"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addAttr"
        >
          添加平台属性
        </el-button>
        <!-- 表格组件 -->
        <el-table
          :data="attrList"
          :border="true"
          style="width: 100%; margin: 10px 0px"
        >
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80"
          />
          <el-table-column prop="attrName" label="属性名称" width="120" />
          <el-table-column label="属性值名称">
            <template #default="{ row }">
              <el-tag
                type="primary"
                v-for="item in row.attrValueList"
                :key="item.id"
                style="margin: 0 4px"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="primary"
                icon="Edit"
                circle
                @click="updateAttr(row)"
              />
              <el-popconfirm
                :title="`你确认删除${row.attrName}吗`"
                icon="Delete"
                width="250px"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    icon="Delete"
                    @click="deleteAttr(row.id)"
                    circle
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <!-- 展示添加属性和修改属行 -->
        <!-- 表单组件 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性名称"
              v-model="attrParmas.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- 按钮组件 -->
        <el-button
          type="primary"
          icon="Plus"
          :disabled="attrParmas.attrName ? false : true"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button @click="cancel">取消</el-button>
        <!-- 表单组件 -->
        <el-table
          :border="true"
          style="margin: 10px 0px"
          :data="attrParmas.attrValueList"
        >
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">
              <el-input
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                v-if="row.flag"
                @blur="toLook(row, $index)"
                size="small"
                :ref="(vc: any) => (inputArr[$index] = vc)"
              ></el-input>
              <!-- 展示数据 -->
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #default="{ $index }">
              <el-button
                type="primary"
                size="small"
                icon="Delete"
                @click="attrParmas.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 按钮组件 -->
        <el-button
          type="primary"
          @click="saveAttr"
          :disabled="attrParmas.attrValueList.length > 0 ? false : true"
        >
          保存
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
